from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
import json
import sys
sys.path.append("/")
from app.services.user import UserService
from app.schemas.user import user_schema
from app.extensions import redis
from app.tasks.tasks import get_all_users

users_bp = Blueprint('users', __name__, url_prefix='/users')


#用户注册
@users_bp.route('', methods=['POST'])
def create_user():
    data = request.get_json()

    user, error = UserService.create_user(data)
    if error:
        return jsonify({"error": error}), 400

    redis.delete('all_users')
    return jsonify(user), 200



#发送的json{
#{
    #"username": "john",
    #"email": "john@example.com",
    #"password": "123456",
    #"department": "sale_department"
#}

#返回的json{
  #"created_at": "2025-07-24T06:05:30",
  #"department": "<Department sale_department>",
 # "email": "susan@example.com",
 # "id": 3,
  #"is_active": true,
  #"is_admin": false,
 # "last_login": "2025-07-24T06:05:30",
 #"roles": [
    #"<Role normal_user>"
 # ],
 # "username": "susan"
#}






#管理员查询所有用户信息
@users_bp.route('/admin_users_info', methods=['GET'])
@jwt_required()
def admin_get_users():

    claims = get_jwt()

    # 只有管理员可以访问所有用户
    if not claims.get('is_admin', False):
        return jsonify({"error": "Admin access required"}), 403

    cached_data = redis.get('all_users')
    if cached_data:
        return jsonify({
            'status': 'success',
            'source': 'cache',
            'data': json.loads(cached_data)
        }), 200

    task = get_all_users.delay()
    return jsonify({
        'status': 'processing',
        'task_id': task.id,
        'check_status': f'/tasks/{task.id}'
    }), 202



#发出的access token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis
#返回的json
#{
 # "data": [
  #  {
   #   "created_at": "2025-08-09T19:17:26",
    #  "department": "<Department manager_department>",
   #   "email": "1551406827@qq.com",
    #  "id": 1,
   #   "is_active": true,
   #   "is_admin": true,
   #   "last_login": "2025-08-09T20:45:59",
   #   "roles": [
   #     "<Role general_manager>"
   #   ],
   #   "username": "kgreat"
   # }
  #],
  #"source": "cache",
  #"status": "success"
#}






@users_bp.route('/tasks/<task_id>', methods=['GET'])
def get_task_status(task_id):
    """检查任务状态"""
    task = get_all_users.AsyncResult(task_id)

    if task.state == 'PENDING':
        response = {
            'state': task.state,
            'status': 'Pending...'
        }
    elif task.state == 'PROGRESS':
        response = {
            'state': task.state,
            'progress': task.info.get('progress', 0)
        }
    elif task.state == 'SUCCESS':
        # 将结果存入缓存，有效期1小时
        result = task.info.get('result', [])
        redis.setex('all_users', 3600, json.dumps(result))

        response = {
            'state': task.state,
            'result': result,
            'count': task.info.get('count', 0)
        }
    else:
        response = {
            'state': task.state,
            'error': str(task.info)  # 异常信息
        }

    return jsonify(response), 200

#返回的json
#{
  #"count": 1,
 # "result": [
  #  {
   #   "created_at": "2025-08-09T19:17:26",
   #   "department": "<Department manager_department>",
   #   "email": "1551406827@qq.com",
   #   "id": 1,
   #   "is_active": true,
   #   "is_admin": true,
    #  "last_login": "2025-08-09T20:45:59",
   #   "roles": [
   #     "<Role general_manager>"
   #   ],
   #   "username": "kgreat"
   # }
  #],
  #"state": "SUCCESS"
#}











#管理员查询某一个人信息
@users_bp.route('/admin_user_info/<int:user_id>', methods=['GET'])
@jwt_required()
def admin_get_user(user_id):

    claims = get_jwt()

    # 用户只能访问自己的信息，除非是管理员
    if not claims.get('is_admin', False):
        return jsonify({"error": "Access denied"}), 403

    user = UserService.get_user_by_id(user_id)
    if not user:
        return jsonify({"error": "User not found"}), 404

    return jsonify(user_schema.dump(user)), 200

#发出的access token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis
#返回的json
#{
  #"created_at": "2025-07-25T03:34:10",
  #"email": "john@example.com",
  #"id": 8,
  #"is_active": true,
  #"is_admin": false,
  #"last_login": "2025-07-25T03:34:10",
  #"roles": [
    #"<Role normal_user>"
  #],
  #"username": "john"
#}



#用户查询自己的个人信息
@users_bp.route('/user_info', methods=['GET'])
@jwt_required()
def user_get_user():
    current_user_id = get_jwt_identity()

    user = UserService.get_user_by_id(current_user_id)
    return jsonify(user_schema.dump(user)), 200
#发出的access token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis

#返回的json{
  #"created_at": "2025-07-24T06:05:30",
  #"email": "susan@example.com",
  #"id": 3,
  #"is_active": true,
  #"is_admin": false,
  #"last_login": "2025-07-24T06:12:47",
# "roles": [
# "<Role normal_user>"
# ],
  #"username": "susan"
#}



#用户修改自己的信息，只能修改邮箱和用户名
@users_bp.route('/user_info_update', methods=['PUT'])
@jwt_required()
def update_user():
    current_user_id = get_jwt_identity()

    data = request.get_json()

    user, error = UserService.update_user(current_user_id, data)

    if error:
        return jsonify({"error": error}), 400
    return jsonify(user), 200

#发出的access token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis

#发送的json {
   # "username": "susan"
#}  或
#{
   # "email": "susan@example.com"
#}

#返回的json{
  #"created_at": "2025-07-24T06:05:30",
  #"email": "susan@example.com",
  #"id": 3,
  #"is_active": true,
  #"is_admin": false,
  #"last_login": "2025-07-24T06:12:47",
# "roles": [
# "<Role normal_user>"
# ],
  #"username": "susan"
#}


#用户注销用户自己
@users_bp.route('/delete_user', methods=['DELETE'])
@jwt_required()
def delete_user():

    current_user_id = get_jwt_identity()
    success, error = UserService.delete_user(current_user_id)

    if error:
        return jsonify({"error": error}), 404

    return jsonify({"message": "User deleted"}), 200

#发出的access token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis
#返回的json{
  #"message": "User deleted"
#}




#管理员修改用户信息, is_admin和is_active
@users_bp.route('/admin_user_info_update/<int:user_id>', methods=['PUT'])
@jwt_required()
def admin_update_user(user_id):
    claims = get_jwt()
    if not claims.get('is_admin', False):
        return jsonify({"error": "Access denied"}), 403

    data = request.get_json()

    user, error = UserService.admin_update_user(user_id, data)

    if error:
        return jsonify({"error": error}), 400
    return jsonify(user), 200

#发出的access token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis
#发送的json
#{
  #"is_active": true
#}

#返回的json
#{
  #"created_at": "2025-07-26T04:03:03",
  #"email": "susan@example.com",
  #"id": 9,
  #"is_active": true,
  #"is_admin": false,
  #"last_login": "2025-07-26T04:03:03",
  #"roles": [
  #  "<Role normal_user>"
 # ],
 # "username": "susan"
#}



#总经理role修改其他用户的role
@users_bp.route('/manager_change_user_role/<int:user_id>', methods=['PUT'])
@jwt_required()
def manager_change_user_role(user_id):

    data = request.get_json()

    current_user_id = get_jwt_identity()
    is_manager = UserService.check_manager_changer_user(current_user_id)
    if not is_manager:
        return jsonify({"error": "User is not general manager"}), 404

    user = UserService.get_user_by_id(user_id)
    if not user:
        return jsonify({"error": "User not found"}), 404


    user, error = UserService.manager_change_user_role(user_id, data)

    if error:
        return jsonify({"error": error}), 400

    return jsonify(user), 200

#发出的access token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis
#发送的json
#{
  # "roles": [
   # "financial_manager","production_manager"
  #]
#}

#返回的json
#{
  #"created_at": "2025-07-27T06:59:49",
 # "email": "john@example.com",
 # "id": 3,
 # "is_active": true,
 # "is_admin": false,
 # "last_login": "2025-07-27T06:59:49",
 # "roles": [
   # "<Role financial_manager>",
   # "<Role production_manager>"
  #],
  #"username": "john"
#}





#总经理role修改其他用户的部门department
@users_bp.route('/manager_change_user_department/<int:user_id>', methods=['PUT'])
@jwt_required()
def manager_change_user_department(user_id):

    data = request.get_json()

    current_user_id = get_jwt_identity()
    is_manager = UserService.check_manager_changer_user(current_user_id)
    if not is_manager:
        return jsonify({"error": "User is not general manager"}), 404

    user = UserService.get_user_by_id(user_id)
    if not user:
        return jsonify({"error": "User not found"}), 404



    user, error = UserService.manager_change_user_department(user_id, data)

    if error:
        return jsonify({"error": error}), 400

    return jsonify(user), 200

#发出的access token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis
#发送的json
#{
  #"department":"production_department"
#}

#返回的json
#{
  #"created_at": "2025-07-28T08:43:56",
  #"department": "<Department production_department>",
  #"email": "john@example.com",
  #"id": 2,
  #"is_active": true,
  #"is_admin": false,
  #"last_login": "2025-07-28T08:43:56",
  #"roles": [
    #"<Role normal_user>"
  #],
  #"username": "john"
#}